<?php
session_start();
ini_set('max_execution_time', 60000);
//error_reporting(E_ALL);
ini_set('memory_limit','360M');
include "includes/comunes.php";
 if($_SESSION['usuTipo'] >= 0)
     header("Location:panel.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sistema de Registro de Atencion</title>
<!--libreria jquery central-->
<script src="jquery-ui/js/jquery-1.9.1.js"></script>
<!--fin libreria central-->

<!--Librerias para el combo-->
<script language="JavaScript" type="text/javascript" src="combos/jquery.chainedSelects.js"></script>
<!--fin libreria-->

<!--librerias ui-->
<link href="jquery-ui/css/ui-lightness/jquery-ui-1.10.2.custom.css" rel="stylesheet"/>
<script src="jquery-ui/js/jquery-ui-1.10.2.custom.js"></script>
<!--fin libreria-->
<script language="JavaScript" type="text/javascript">
$(function()
{

	  $( "#menu" ).menu({position: {at: "left bottom"}});
});
</script>
<link href="estilos.css" rel="stylesheet" type="text/css" />
</head>

<body>

<div class="container">
<?php include "includes/head.php"?>
   <div class="content">
       <div class="tituloprincipal">Importacion de Articulos
           <?php include 'includes/submenu.php';?>  
           </div>
       <div class="contenedor">
     <fieldset>
	 <legend>Importar Articulos</legend>
    <form name="frmload" method="post" action="importarArticulos.php" enctype="multipart/form-data">
	    <input type="hidden" name="MAX_FILE_SIZE" value="90000000"> 
        <input type="file" name="file" /> &nbsp; &nbsp; &nbsp; <input type="submit" value="----- IMPORTAR -----" />
    </form>
	</fieldset>
	<fieldset>
	 <legend>Eliminar Base de Articulos</legend>
	 <form name="frmload" method="post" action="importarArticulos.php" enctype="multipart/form-data">
        <input type="submit" name="eliminar" value="Eliminar Base" /> &nbsp; &nbsp; &nbsp; <span style="color:red;">Cuidado, esta opcion elimina todos los articulos de la base de datos</span>
    </form>
	 </fieldset>
    <div id="show_excel">
    	<?php
        if($_POST['eliminar']) {
			$sql="delete from productos";
			$eje=cons_sql_up($sql);
			
			$sql="alter table productos auto_increment=1";
			$eje=cons_sql_up($sql);
			echo '<span style="color:red;">Se eliminaron correctamente los datos de articulos</span>';
		}
		else
		if($_FILES['file']['name'] != '')
		{

			require_once 'includes/Classes/PHPExcel/IOFactory.php';

			//Funciones extras

			function get_cell($cell, $objPHPExcel){
				//select one cell
				$objCell = ($objPHPExcel->getActiveSheet()->getCell($cell));
				//get cell value
				return $objCell->getvalue();
			}

			function pp(&$var){
				$var = chr(ord($var)+1);
				return true;
			}

			$name	  = $_FILES['file']['name'];
			$tname 	  = $_FILES['file']['tmp_name'];
			$type 	  = $_FILES['file']['type'];

			if($type == 'application/vnd.ms-excel')
			{
				// Extension excel 97
				$ext = 'xls';
			}
			else if($type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
			{
				// Extension excel 2007 y 2010
				$ext = 'xlsx';
			}else{
				// Extension no valida
				echo -1;
				exit();
			}

			$xlsx = 'Excel2007';
			$xls  = 'Excel5';
			
			//creando el lector
			$objReader = PHPExcel_IOFactory::createReader($$ext);
	        
			//cargamos el archivo
			$objPHPExcel = $objReader->load($tname);
			 //$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory;
		    //	PHPExcel_Settings::setCacheStorageMethod($cacheMethod);

			//echo $objPHPExcel->getSheetCount();
			$dim = $objPHPExcel->getActiveSheet()->calculateWorksheetDimension();
            // echo $dim ;die();
			// list coloca en array $start y $end
			list($start, $end) = explode(':', $dim);

			if(!preg_match('#([A-Z]+)([0-9]+)#', $start, $rslt)){
				return false;
			}
			list($start, $start_h, $start_v) = $rslt;
			if(!preg_match('#([A-Z]+)([0-9]+)#', $end, $rslt)){
				return false;
			}
			list($end, $end_h, $end_v) = $rslt;
		
			//empieza  lectura vertical
			//$table = "<table  border='1'>";
                        $ban=1;
                        $f=0;
			for($v=$start_v+1; $v<=$end_v; $v++){
				//empieza lectura horizontal
				//$table .= "<tr>";
				for($h=$start_h; ord($h)<=ord($end_h); pp($h)){
					$cellValue = get_cell($h.$v, $objPHPExcel);
//                                        
                                        
                                        //verifico si el codigo esta cargado
//                                        if($cellValue !== null){
                                            if($h=='A'){
                                              $ban=verificar_importacion_codigo($cellValue);
                                            }
                                              //si $ban ==0 no existe , si es =1 Existe
                                                 if($ban==0)
                                                     $datos[$f][1]=get_cell('A'.$v, $objPHPExcel);
                                                     $datos[$f][2]=get_cell('B'.$v, $objPHPExcel);
													 $datos[$f][3]=get_cell('C'.$v, $objPHPExcel);
													 $datos[$f][4]=get_cell('D'.$v, $objPHPExcel);
                                                     
//                                        }


					//$table .= "<td>";
//					if($cellValue !== null){
//						$table .= $cellValue;
//					}
					//$table .= "</td>";
				}
				//$table .= "</tr>";
                                $f++;
			}
			//$table .= "</table>";

			//echo $table;
                        $tot=0;
                        $art="";
                        for($i=0;$i<=count($datos);$i++){
                           $ins=insertar_codigo($datos[$i][1], $datos[$i][2],$datos[$i][3],$datos[$i][4]);
                             if($ins){
                              $art.=" Artículo actualizado: ".$datos[$i][1]."  ".$datos[$i][2]."<br>";
                              $tot++;
                             }

                        }


                        echo "Se actualizaron ".$tot." artículos.<br><br>".$art;

                        
		}
		?>
    </div>
       </div>
       <div class="clear"></div>
   <br>
   </div>
  <?php include "includes/pie.php"?>
  
</div>
</body>
</html>